package com.situ.personal.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.personal.util.JDBCUtil;
import com.situ.personal.util.JDBCUtil_输入姓名练习;

@WebServlet("/student")
public class StudentServlet extends HttpServlet{
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		/**
		 * 获取参数
		 * 把 传入的name  看看数据库里有木有重名的
		 * 
		 * 设置返回data utf-8格式
		 * 返回 data（"isExist" : isExist ）
		 */
		String name =  req.getParameter("name");
		boolean isExist = checkName(name);
		System.out.println("数据库返回："+isExist);
		
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().write("{\"isExist\": " + isExist + "}");
	}

	private boolean checkName(String name) {
		/**
		 * 看看数据库查没查到 名字一样的
		 * 查到了  结果集 isExist=true,,没查到默认isExist = false
		 * 返回isExist
		 */
		boolean isExist = false; 
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		
		try { // DBUtils
			connection = JDBCUtil_输入姓名练习.getConnection();
			String sql = "select * from student where name=?";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, name);
			System.out.println(preparedStatement);
			resultSet = preparedStatement.executeQuery();
			// 判断下一行有没有，有返回true，并指向这一行，没有返回false
			while (resultSet.next()) {
				// 可以使用列名，也可以使用列的下标
				isExist=true;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil_输入姓名练习.close(resultSet, preparedStatement, connection);
		}
		return isExist;
	}
}
